package com.atguigu.uitls;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class DimUtil {

    public static JSONObject getDimInfo(Connection connection, String tableName, String pk) throws InvocationTargetException, SQLException, InstantiationException, IllegalAccessException {

        //查询Redis
        Jedis jedis = RedisUtil.getJedis();
        String redisKey = "DIM:" + tableName + ":" + pk;
        String dimInfoStr = jedis.get(redisKey);
        if (dimInfoStr != null) {
            jedis.expire(redisKey, 24 * 60 * 60);
            jedis.close();
            return JSON.parseObject(dimInfoStr);
        }

        //拼接查询语句
        String sql = "select * from " + GmallConfig.HBASE_SCHEMA + "." + tableName + " where id='" + pk + "'";

        //查询
        List<JSONObject> list = JDBCUtil.queryResult(connection,
                sql
                , JSONObject.class,
                false);
        JSONObject dimInfo = list.get(0);

        //将数据写入Redis
        jedis.set(redisKey, dimInfo.toJSONString());
        jedis.expire(redisKey, 24 * 60 * 60);
        jedis.close();

        //返回结果
        return dimInfo;

    }

    public static void deleteRedisDimInfo(String tableName, String pk) {
        String redisKey = "DIM:" + tableName + ":" + pk;
        Jedis jedis = RedisUtil.getJedis();
        jedis.del(redisKey);
        jedis.close();
    }

    public static void main(String[] args) throws Exception {

        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        long start = System.currentTimeMillis();
        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "17")); //241 251 253
        long end = System.currentTimeMillis();
        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "17")); //9
        long end2 = System.currentTimeMillis();

        System.out.println(end - start);
        System.out.println(end2 - end);

        connection.close();

    }

}
